package itsm.isperp.job;

import java.util.Calendar;
import java.util.Date;

import javax.servlet.ServletContext;
import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.module.controller.api.wechat.v2.WechatController;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.context.ContextLoader;

/**
 * 
 * 计划任务作业
 * 
 * @author lizx
 * @date 2013-7-31
 * 
 */
@Service
public class WechatJob implements Job {
	
	private String corpid = ContextHolder.getConfigByKey("wechatCpAppId");
	

	public static final Logger logger = LoggerFactory
			.getLogger(WechatJob.class);

	@Override
	public void execute(JobExecutionContext context)
			throws JobExecutionException {
		logger.debug("generate plan task.");
		ServletContext servletContext = ContextLoader.getCurrentWebApplicationContext().getServletContext();
		String secret = "kjDWR9ippgJ_53laZa4o4MJYIGP5rJYPi2t9TA_Uvew";
		JSONObject json;
		try {
			json = this.httpGetAccessToken(secret);
			String accessToken = json.getString("access_token");
	        int expiresIn = json.getInt("expires_in");
	        
	        Date now = new Date();
	        Date accessTokenTimeOut = new Date(now.getTime() + (expiresIn * 1000));
	        servletContext.setAttribute("wxAccessToken" + secret, accessToken);
	        servletContext.setAttribute("wxAccessTokenTimeOut" + secret, accessTokenTimeOut);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
        
		
		
		WechatController wechatController=ContextHolder.getSpringBean("wechatController");
		Date date = new Date();
		Calendar start = Calendar.getInstance();
		start.setTime(date);
		start.set(Calendar.HOUR_OF_DAY, 0);
		start.set(Calendar.MINUTE, 0);
		start.set(Calendar.SECOND, 1);
		
		Calendar end = Calendar.getInstance();
		end.setTime(date);
		end.set(Calendar.HOUR_OF_DAY, 23);
		end.set(Calendar.MINUTE, 59);
		end.set(Calendar.SECOND, 59);
		
		try {
			wechatController.syncCheckinData1(servletContext, start.getTime(), end.getTime());
		} catch (Exception e) {
			logger.error("任务生产失败", e);
		}
	}
	
	private JSONObject httpGetAccessToken(String secret)
            throws Exception {
		secret = "kjDWR9ippgJ_53laZa4o4MJYIGP5rJYPi2t9TA_Uvew";
        String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpid + "&corpsecret=" + secret;
        try {
            return httpGet(url);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new Exception("获取微信AccessToken失败，原因是：" + e.getMessage());
        }
    }
	
	private JSONObject httpGet(String url)
            throws Exception {
        HttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader("Content-Type", "application/json; charset=UTF-8");

        HttpResponse httpResponse = httpClient.execute(httpGet);
        HttpEntity entity = httpResponse.getEntity();

        String response = EntityUtils.toString(entity);
        JSONObject json = new JSONObject(response);

        return json;
    }
}